package com.zjdiepu.www.util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import org.apache.commons.lang.StringUtils;

/**
 * 拼音工具
 * @author xiongxiaotun
 *
 */
public class PinYinUtil {
	public static final int DEAULT_MAX_LIMIT = 50;
	
	/**
	 * 获取汉语拼音
	 * @param chineses 中文字符串
	 * @return
	 */
	public static String toPinYin(String chineses) {
		return toPinYin(chineses, false);
	}
	
	/**
	 * 获取汉语拼音
	 * @param chineses 中文字符串
	 * @param limit 是否限制拼音长度（默认长度50）
	 * @return
	 */
	public static String toPinYin(String chineses, boolean limit) {
		return toPinYin(chineses, limit, DEAULT_MAX_LIMIT);
	}
	
	/**
	 * 获取汉语拼音
	 * @param chineses 中文字符串
	 * @param limit 是否限制拼音长度
	 * @param maxLimit 最大长度
	 * @return
	 */
	public static String toPinYin(String chineses, boolean limit, int maxLimit) {
		return toPinYin(chineses, limit, maxLimit, false);
	}
	
	/**
	 * 获取汉语拼音
	 * @param chineses 中文字符串
	 * @param limit 是否限制拼音长度
	 * @param maxLimit 最大长度
	 * @param remain 是否保存非中文字符
	 * @return
	 */
	public static String toPinYin(String chineses, boolean limit, int maxLimit,	boolean remain) {
		String pinyin = "";
		if (StringUtils.isBlank(chineses)) {
			return pinyin;
		}
		HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat();
		outputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE); // 输出拼音不带声调// 如：lu
		outputFormat.setVCharType(HanyuPinyinVCharType.WITH_V); // ǜ的输出格式设置 'ü' 输出为 "v"
		outputFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE); // 输出拼音为小写
		int count = 0;
		boolean first = true;
		for (String chinese : chineses.split("")) {
			try {
				String currentPinyin = PinyinHelper.toHanYuPinyinString(chinese, outputFormat, "", remain);
				if(StringUtils.isBlank(currentPinyin)) {
					continue;
				}
				count += currentPinyin.length();
				if(limit && count > maxLimit) {
					break;
				}
				if(first) {
					first = false;
				} else {
					pinyin += " ";
				}
				pinyin += currentPinyin.toUpperCase();
			} catch (BadHanyuPinyinOutputFormatCombination e) { //拼音格式出问题
				e.printStackTrace();
			}
		}
		return pinyin;
	}
	
	public static void main(String[] args) {
		System.out.println(toPinYin("啊啊啊aaa啊过"));
	}
}
